<template>
    <div class="container">
        <Breadcrumb :items="['store', 'cat']" />
        <a-card class="general-card" title="商品分类管理">
            <a-row>
                <a-col :flex="1">
                    <a-space>
                        <a-button type="primary" @click="openAddModal">
                            <template #icon>
                                <icon-plus />
                            </template>
                            添加分类
                        </a-button>
                    </a-space>
                </a-col>
            </a-row>
            <a-divider style="margin: 16px 0" />
            <a-table :data="tableData" :loading="loading" :pagination="false" row-key="id" :indent-size="20"
                :children-key="'children'" :default-expand-all-rows="true">
                <template #columns>
                    <a-table-column title="分类名称" data-index="name">
                        <template #cell="{ record }">
                            <span>{{ record.name }}</span>
                        </template>
                    </a-table-column>
                    <a-table-column title="图片" width="100">
                        <template #cell="{ record }">
                            <a-image v-if="record.image_url" :src="record.image_url" :width="50" :height="50" fit="cover" />
                            <span v-else class="text-gray-400">-</span>
                        </template>
                    </a-table-column>
                    <a-table-column title="自定义URL" data-index="url" width="180">
                        <template #cell="{ record }">
                            <span>{{ record.url || '-' }}</span>
                        </template>
                    </a-table-column>
                    <a-table-column title="排序" data-index="sort" width="100" />
                    <a-table-column title="创建时间" data-index="created_at" width="180">
                        <template #cell="{ record }">
                            {{ formatDate(record.created_at) }}
                        </template>
                    </a-table-column>
                    <a-table-column title="操作" width="200" fixed="right">
                        <template #cell="{ record }">
                            <a-space>
                                <a-link @click="openEditModal(record)">编辑</a-link>
                                <a-popconfirm content="确定要删除该分类吗？" @ok="handleDelete(record)">
                                    <a-link>删除</a-link>
                                </a-popconfirm>
                            </a-space>
                        </template>
                    </a-table-column>
                </template>
            </a-table>
        </a-card>

        <!-- 添加分类弹窗 -->
        <a-modal v-model:visible="addModalVisible" title="添加分类" @ok="handleAdd" @cancel="closeAddModal"
            :confirm-loading="addLoading">
            <a-form ref="addFormRef" :model="addForm" :rules="addRules" layout="vertical">
                <a-form-item field="name" label="分类名称" required>
                    <a-input v-model="addForm.name" placeholder="请输入分类名称" />
                </a-form-item>
                <a-form-item label="图片" :rules="[{ required: true }]">

                    <a-upload list-type="picture" v-model="addForm.image" :custom-request="handleUpload" :limit="1"
                        :file-list="fileList" image-preview @before-remove="beforeRemove" />
                    <template #extra>
                        <div>请保持图片比例为1:1</div>
                    </template>
                </a-form-item>
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item field="parent_id" label="父级分类">
                            <a-select v-model="addForm.parent_id" placeholder="请选择父级分类（可选）" allow-clear>
                                <a-option :value="0">顶级分类</a-option>
                                <a-option v-for="item in parentOptions" :key="item.id" :value="item.id">
                                    {{ item.name }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item field="sort" label="排序">
                            <a-input-number v-model="addForm.sort" placeholder="请输入排序值" :min="0" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item field="url" label="自定义URL">
                            <a-input v-model="addForm.url" placeholder="选填"  style="width: 100%" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>

        <!-- 编辑分类弹窗 -->
        <a-modal v-model:visible="editModalVisible" title="编辑分类" @ok="handleEdit" @cancel="closeEditModal"
            :confirm-loading="editLoading">
            <a-form ref="editFormRef" :model="editForm" :rules="editRules" layout="vertical">
                <a-form-item field="name" label="分类名称" required>
                    <a-input v-model="editForm.name" placeholder="请输入分类名称" />
                </a-form-item>
                <a-form-item label="图片" :rules="[{ required: true }]">
                    <a-upload list-type="picture" :custom-request="handleEditUpload" :limit="1"
                        :file-list="editFileList" image-preview @before-remove="beforeEditRemove" />
                    <template #extra>
                        <div>请保持图片比例为1:1</div>
                    </template>
                </a-form-item>
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item field="parent_id" label="父级分类">
                            <a-select v-model="editForm.parent_id" placeholder="请选择父级分类（可选）" allow-clear>
                                <a-option :value="0">顶级分类</a-option>
                                <a-option v-for="item in editParentOptions" :key="item.id" :value="item.id">
                                    {{ item.name }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item field="sort" label="排序">
                            <a-input-number v-model="editForm.sort" placeholder="请输入排序值" :min="0" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item field="url" label="自定义URL">
                            <a-input v-model="editForm.url" placeholder="选填"  style="width: 100%" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { FileItem } from '@arco-design/web-vue';
import { getGoodsCatList, createGoodsCat, updateGoodsCat, deleteGoodsCat } from '@/api/goodsCat';
import type { GoodsCatItem, CreateGoodsCatRequest, UpdateGoodsCatRequest } from '@/api/goodsCat';
import { uploadFile } from '@/api/upload';

const loading = ref(false);
const tableData = ref<GoodsCatItem[]>([]);
const addModalVisible = ref(false);
const addLoading = ref(false);
const addFormRef = ref();
const fileList = ref<{ url: string }[]>([]);

// 编辑相关变量
const editModalVisible = ref(false);
const editLoading = ref(false);
const editFormRef = ref();
const editFileList = ref<{ url: string }[]>([]);

const addForm = reactive<CreateGoodsCatRequest>({
    name: '',
    parent_id: 0,
    sort: 0,
    image: '',
});

const addRules = {
    name: [
        { required: true, message: '请输入分类名称' },
        { minLength: 1, maxLength: 50, message: '分类名称长度在1-50个字符之间' },
    ],
};

const editForm = reactive<UpdateGoodsCatRequest>({
    id: 0,
    name: '',
    parent_id: 0,
    sort: 0,
    image: '',
});

const editRules = {
    name: [
        { required: true, message: '请输入分类名称' },
        { minLength: 1, maxLength: 50, message: '分类名称长度在1-50个字符之间' },
    ],
};


const handleUpload = async (option: any) => {
    try {
        const { onProgress, onError, onSuccess, fileItem, name } = option;

        const uploadFormData = new FormData();
        uploadFormData.append('file', fileItem.file);
        const { data } = await uploadFile(uploadFormData);
        addForm.image = data.path;
        fileList.value = [{ url: data.url }];
        Message.success('上传成功');
        return {
            abort: () => { },
        };
    } catch (err) {
        Message.error('上传失败');
        return {
            abort: () => { },
        };
    }
};

const beforeRemove = (file: any) => {
    addForm.image = '';
    fileList.value = [];
    return true;
};

const handleEditUpload = async (option: any) => {
    try {
        const { onProgress, onError, onSuccess, fileItem, name } = option;

        const uploadFormData = new FormData();
        uploadFormData.append('file', fileItem.file);
        const { data } = await uploadFile(uploadFormData);
        editForm.image = data.path;
        editFileList.value = [{ url: data.url }];
        Message.success('上传成功');
        return {
            abort: () => { },
        };
    } catch (err) {
        Message.error('上传失败');
        return {
            abort: () => { },
        };
    }
};

const beforeEditRemove = (file: any) => {
    editForm.image = '';
    editFileList.value = [];
    return true;
};

// 父级分类选项
const parentOptions = ref<GoodsCatItem[]>([]);
const editParentOptions = ref<GoodsCatItem[]>([]);

// 获取分类列表
const fetchData = async () => {
    loading.value = true;
    try {
        const res = await getGoodsCatList();
        console.log('API响应:', res);
        if (res.code === 20000) {
            tableData.value = res.data.list;
            // 设置父级分类选项（只显示顶级分类）
            parentOptions.value = res.data.list.filter(item => item.fid === 0);
            editParentOptions.value = res.data.list.filter(item => item.fid === 0);

        } else {
            Message.error(res.msg || '获取分类列表失败');
        }
    } catch (error) {
        console.error('获取分类列表错误:', error);
        Message.error('获取分类列表失败');
    } finally {
        loading.value = false;
    }
};

// 打开添加弹窗
const openAddModal = () => {
    addModalVisible.value = true;
    addForm.name = '';
    addForm.parent_id = 0;
    addForm.sort = 0;
    addForm.image = '';
};

// 关闭添加弹窗
const closeAddModal = () => {
    addModalVisible.value = false;
    addFormRef.value?.resetFields();
};

// 打开编辑弹窗
const openEditModal = (record: GoodsCatItem) => {
    editModalVisible.value = true;
    editForm.id = record.id;
    editForm.name = record.name;
    editForm.parent_id = record.fid;
    editForm.sort = record.sort;
    editForm.image = record.image || '';
    
    // 设置父级分类选项（排除当前分类及其子分类）
    editParentOptions.value = tableData.value.filter(item => 
        item.fid === 0 && item.id !== record.id
    );

    if(record.image != ''){
        editFileList.value = [{ uid: record.id, url: record.image_url}];
    }else{
        editFileList.value = [];
    }
};

// 关闭编辑弹窗
const closeEditModal = () => {
    editModalVisible.value = false;
    editFormRef.value?.resetFields();
    editForm.id = 0;
    editForm.name = '';
    editForm.parent_id = 0;
    editForm.sort = 0;
    editForm.image = '';
    editFileList.value = [];

    editForm.url = '';
};

// 添加分类
const handleAdd = async () => {
    addLoading.value = true;
    try {
        const res = await createGoodsCat(addForm);
        if (res.code === 20000) {
            Message.success('添加成功');
            closeAddModal();
            fetchData();
        } else {
            Message.error(res.msg || '添加失败');
        }
    } catch (error) {
        Message.error('添加失败');
    } finally {
        addLoading.value = false;
    }
};

// 编辑分类
const handleEdit = async () => {
    editLoading.value = true;
    try {
        const res = await updateGoodsCat(editForm);
        if (res.code === 20000) {
            Message.success('更新成功');
            closeEditModal();
            fetchData();
        } else {
            Message.error(res.msg || '更新失败');
        }
    } catch (error) {
        Message.error('更新失败');
    } finally {
        editLoading.value = false;
    }
};

// 删除分类
const handleDelete = async (record: GoodsCatItem) => {
    try {
        const res = await deleteGoodsCat(record.id);
        if (res.code === 20000) {
            Message.success('删除成功');
            fetchData();
        } else {
            Message.error(res.msg || '删除失败');
        }
    } catch (error) {
        if (error !== 'cancel') {
            Message.error('删除失败');
        }
    }
};

// 格式化日期
const formatDate = (timestamp: number) => {
    if (!timestamp) return '';
    return new Date(timestamp * 1000).toLocaleString('zh-CN');
};

onMounted(() => {
    fetchData();
});
</script>

<style scoped>
.container {
    padding: 0 20px 20px 20px;
}

.general-card {
    min-height: 500px;
}
</style>
